﻿
using iTool_Cetector.Global;
using LibGit2Sharp;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace iTool_Cetector.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PluginsController : ControllerBase
    {
        [HttpPost("{repoName}")]
        public async Task<int> Upgrade(string repoName)
        {


            Utils.Logger($"Upgrade {repoName}");


            if (string.IsNullOrWhiteSpace(GlobalUtils.SeedString))
            {
                throw new Exception("seed is null");
            }

            string repoPath = "/var/iTool/" + repoName;
#if DEBUG
            repoPath = @"D:\StressTesting\" + repoName;
#endif

            // 稍等一会
            await Task.Delay(3000);

            if (Directory.Exists(repoPath))
            {
                this.Pull(repoPath);
            }
            else
            {
                this.Clone($"{GlobalUtils.GatewayUrl.TrimEnd('/')}/{repoName}.git", repoPath);
            }

            string basePath = "";
            if (repoName.ToLower() == "iTool-Server-Plugins".ToLower())
            {
                basePath = "/var/iTool/iTool-Server";
            }
            else if (repoName.ToLower() == "iTool-Connector-Plugins".ToLower())
            {
                basePath = "/var/iTool/iTool-Connector";
            }
            else
            {
                return 0;
            }

            var dlls = Directory.GetFiles(repoPath, "*.dll", SearchOption.TopDirectoryOnly);

            if (Directory.Exists(basePath))
            {
                if (!Directory.Exists($"{basePath}/Plugins"))
                {
                    Directory.CreateDirectory($"{basePath}/Plugins");
                }
            }
            else
            {
                // 本地没有启动该服务
                return 1;
            }

            foreach (var dll in dlls)
            {
                var fileName = $"{basePath}/Plugins/{Path.GetFileName(dll)}";
                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
                System.IO.File.Copy(dll, fileName);
            }

            return 1;
        }


        public void Clone(string server,string repoPath) 
        {
            Utils.Logger($"Clone {server} - {repoPath}");

            var co = new CloneOptions();
            co.IsBare = false;
            co.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials {
                //Username = "Administrator" ?? GlobalUtils.PublicIp,
                //Password = "zhuJIAN30.3.." ?? GlobalUtils.SeedString
                Username = GlobalUtils.PublicIp, 
                Password = GlobalUtils.SeedString
            };
            string logMessage = Repository.Clone(server, repoPath, co);
            Console.WriteLine(logMessage);
        }

        public void Pull(string repoPath) 
        {
            Utils.Logger($"Pull {repoPath}");

            using (var repo = new Repository(repoPath))
            {
                var author = new Signature("U", "139939967@qq.com", DateTimeOffset.Now);
                Commands.Pull(repo, author, new PullOptions
                {
                    FetchOptions = new FetchOptions
                    {
                        CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { 
                            Username = GlobalUtils.PublicIp, 
                            Password = GlobalUtils.SeedString
                        }
                    }
                });
            }
        }

    }
}
